/*
 * DA2.c
 *
 *  Author: Henry Chan
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>
void delay();

int main(void)
{
	DDRB = 0xFF;			//Set PORTB to output
	DDRC = 0xFF;			//Set PORTC to output
	DDRD = 0x04;			//Set Port.D2(INT0) to input
	PORTB = 0x00;			//Initialize PORTB to 0
	PORTC = 0x00;			//Initialize PORTC to 0
	TCNT0 = 0x00;			//Initialize Timer0
	//TCCR0A = 0x00;			//Set Timer0 mode to Normal mode
	//TCCR0B = 0x06;			//External Clock on falling edge
	//TCNT1H = 0x85;			//Set Timer1 count value to 34286
	//TCNT1L = 0xEE;			//for delay of 0.25s
	//TCCR1A = 0x00;			//Set Timer1 mode to Normal mode
	//TCCR1B = 0x03;			//64 Prescalar
	//TCNT2 = 0xFE;			//Intialize Timer2
	//TCCR0A = 0x00;			//Normal mode, no prescalar
	//TCCR0B = 0x01;
	//TIMSK0 = (1 << TOIE0);	//Enable Timer0 Overflow interrupt
	TIMSK1 = (1 << TOIE1);	//Enable Timer1 Overflow interrupt
	//TIMSK2 = (1 << TOIE2);	//Enable Timer2 Overflow interrupt
	EIMSK = (1 << INT0);	//Enable INT0 Interrupt
	EICRA = (1 << ISC01);	//Falling Edge of INT0 generates interrupt request
	sei();
    while(1)
    {
		PORTB = TCNT0;				//Output 8-bit Counter to PORTB
		delay();					//elapse 0.25s
		if((PORTC && (1 << 0)) == 0)	//If wave is falling edge
		TCNT0++;					//Increment Count
		if(TCNT0%10 == 0)			//If this is a 10th falling edge
		PORTC ^= (1 << 1);			//Toggle 9th LED
		if(TCNT2%2 == 0)			//If this is 2nd falling edge of 9th LED
		PORTC ^= (1 << 2);			//Toggle the 10th LED
    }
}
ISR(INT0_vect){
	TCNT2++;
}
ISR(TIMER1_OVF_vect){		//Timer1 has completed a 0.25s cycle
	PORTC = PORTC^(1 << 0);		//Toggle PORTC.0
	TCCR1A = 0x00;			//Stop Timer1
	TCCR1B = 0x00;
	TIFR1 = 1<<TOV1;		//Reset flag register
}
void delay(){
	TCNT1H = 0x85;			//Set Timer1 count value to 34286
	TCNT1L = 0xEE;			//for delay of 0.25s
	TCCR1A = 0x00;			//Set Timer1 mode to Normal mode
	TCCR1B = (1 << CS11) | (1 << CS10);	//64 Prescalar
	while((TIFR1 & (1<<TOV1)) == 0){} //Run for 0.25s
}